<template>
    <div class="app-container calzzRulellPage">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input
            v-model="queryParams.ruleName"
            placeholder="请输入规则名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="班级" prop="clazzId">
          <el-select v-model="queryParams.clazzId" placeholder="请选择班级" clearable>
            <el-option
              v-for="item in clazzList"
              :key="item.id"
              :label="item.clazzName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学生类型" prop="studentTypes">
          <el-select v-model="queryParams.studentTypes" placeholder="请选择学生类型">
            <el-option
              v-for="dict in dict.type.student_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="招生年份" prop="zsYear">
          <el-date-picker v-model="queryParams.zsYear" value-format="yyyy"  type="year" placeholder="选择年" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:clazz:rule:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:clazz:rule:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:clazzRule:remove']"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="规则名称" align="center" prop="ruleName" :show-overflow-tooltip="true" />
        <el-table-column label="班级" align="center" prop="clazzName" />
        <el-table-column label="学生类型" align="center" :formatter="formatInnerStudentTypeName" key="studentTypes" />
        <el-table-column label="招生年份" align="center" prop="zsYear" />
        <el-table-column label="状态" align="center" prop="status"  :formatter="formatInnerStatus"/>
        <el-table-column label="规定人数" align="center" prop="totalCount" />
        <el-table-column label="实际人数" align="center" prop="actualCount" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:clazz:rule:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:clazz:rule:remove']"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="handleExecute(scope.row)"
              v-hasPermi="['system:clazz:rule:execute']" 
              v-if="scope.row.status == 0"
            >执行</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
      <!-- 添加或修改定时分班规则对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
        <el-form ref="form" :model="form" :rules="rule" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="规则名称" prop="ruleName">
                <el-input v-model="form.ruleName" placeholder="请输入规则名称" style="width: 220px" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班级" prop="clazzName">
                <el-select v-model="form.clazzName" placeholder="请选择班级"  @change="getClazzDetail(form.clazzName)">
                  <el-option
                    v-for="item in clazzList"
                    :key="item.id"
                    :label="item.clazzName"
                    :value="item.id + ',' +item.clazzName"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学生类型" prop="studentTypes">
                <el-select v-model="form.studentTypes" multiple placeholder="请选择学生类型">
                  <el-option
                    v-for="dict in dict.type.student_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="招生年份" prop="zsYear">
                <el-date-picker v-model="form.zsYear" value-format="yyyy"  type="year" placeholder="选择年" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="招生列表" prop="majorList"><br>
                <el-row v-for="(item,index) in form.majorList" :key="index" style="margin: 0 0 20px -60px">
                  <el-col :span="10">
                    <el-form-item label="专业" :prop="`majorList[${index}].majorName`" :rules="rule.majorName">
                      <el-select v-model="item.majorName" placeholder="请选择专业" clearable @change="getMajorDetail(item.majorName,index)">
                        <el-option
                          v-for="i in majorList"
                          :key="i.id"
                          :label="i.majorName"
                          :value="i.id + ',' + i.majorName"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item label="学生数量" :prop="`majorList[${index}].studentCount`" :rules="rule.studentCount">
                      <el-input v-model="item.studentCount" type="number"/>
                    </el-form-item>
                  </el-col>
                  <el-button type="primary" plain size="mini" @click="delMajor(index)" style="margin-left: 20px;">删除</el-button>
                </el-row>
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addMajor">添加专业</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { clazzList, majorList } from "@/api/student";
  import { clazzRuleList, addClazzRule, updateClazzRule, delClazzRule, getClazzRule, executeClazzRule } from "@/api/clazzRule";
  export default {
    dicts: ['sys_user_sex','polical_status','student_type','student_zsstatus'],
    name: "calzzRulell",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 定时分班规则表格数据
        dataList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          ruleName: undefined,
          clazzId: undefined,
          majorId: undefined,
          zsYear: undefined
        },
        // 表单参数
        form: {
            ruleName:undefined,
            clazzId: undefined,
            clazzName:undefined,
            studentTypes:undefined,
            zsYear:undefined,
            majorList:[]
        },
        // 表单校验
        rule: {
          ruleName: [
            { required: true, message: "规则名称不能为空", trigger: "blur" }
          ],
          clazzName: [
            { required: true, message: "班级不能为空", trigger: "blur" }
          ],
          studentTypes: [
            { required: true, message: "学生类型不能为空", trigger: "blur" }
          ],
          zsYear: [
            { required: true, message: "招生年份不能为空", trigger: "blur" }
          ],
          majorList: [
            { required: true, message: "招生列表不能为空", trigger: "blur" }
          ],
          studentCount: [
            { required: true, message: "学生数量不能为空", trigger: "blur" },
          ],
          majorName: [
            { required: true, message: "专业不能为空", trigger: "blur" }
          ],
        },
        majorList:[],
        clazzList:[]
      };
    },
    created() {
      this.getList();
      this.getSelectList()
    },
    methods: {
      /** 查询定时分班规则列表 */
      getList() {
        this.loading = true;
        clazzRuleList(this.queryParams).then(res => {
          this.dataList = []
          this.dataList = res.rows;
          this.total = res.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          ruleName:undefined,
          clazzId:undefined,
          clazzName:undefined,
          studentTypes:undefined,
          zsYear:undefined,
          majorList:[]
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加分班规则";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids;
        getClazzRule(id).then(response => {
          this.form = response.data;
          this.form.studentTypes = this.form.studentTypes.split(',')
          this.open = true;
          this.title = "修改分班规则";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.studentTypes = this.form.studentTypes.join(',')
            if (this.form.id != undefined) {
              updateClazzRule(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addClazzRule(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除？').then(function() {
          return delClazzRule(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      // 执行按钮操作
      handleExecute(row){
         this.$modal.confirm('请仔细检查分班规则是否正确，此规则仅可执行一次，是否确认执行？').then(function() {
            return executeClazzRule(row.id);  
          }).then(() => { 
            this.getList();
            this.$modal.msgSuccess("执行成功");
        }).catch(() => {});
      },
      // 获取下拉接口
      getSelectList(){
        // 获取班级下拉接口
        clazzList().then(res=>{
          this.clazzList = res
        })
      },
      // 点击获取专业下拉及学生数量框
      addMajor(){
        // 获取专业下拉接口
        majorList().then(res=>{
          this.majorList = res
        })
        this.form.majorList.push({studentCount:null,majorId:null})
      },
      // 删除已添加专业
      delMajor(i){
        this.form.majorList.splice(i,1)
      },
      // 获取班级id与name
      getClazzDetail(a){
        this.form.clazzId = Number(a.split(',')[0])
        this.form.clazzName = a.split(',')[1]
      },
      // 获取所选专业id与name
      getMajorDetail(a,i){
        this.form.majorList[i].majorId = Number(a.split(',')[0])
        this.form.majorList[i].majorName = a.split(',')[1]
      },
      // 列表学生类型回显
      formatInnerStudentTypeName(row){
        let types = row.studentTypes.split(',')
        let names = []
        types.forEach(i =>{
           this.dict.type.student_type.forEach(j=>{
             if(i == Number(j.value)){
              names.push(j.label)
             }
           })
         })
        names = names.join('，')
        return names
      },
      // 列表状态回显
      formatInnerStatus(row){
        return row.status == 0 ? '启用' : '禁用'
      }
    }
  };
</script>

<style>

</style>